package com.wdd.myplatform.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.wdd.myplatform.entity.BlackListExportExcel;
import com.wdd.myplatform.entity.BlackListImportExcel;
import com.wdd.myplatform.utils.ExcelCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 导入带图片的excel
 * @author Administrator
 */
@RestController
@RequestMapping("/excelWithPictureController")
@Slf4j
public class EasyPOIExcelWithPictureController {

//    @Autowired
//    private FdfsToolsUtil fdfsToolsUtil;

    @PostMapping("/testImport")
    public void testImport(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        //标题行，如果没有就不填，否则导入时数据会变成null
//        params.setTitleRows(1);
        //头行，例如：姓名、地址、联系方式  这些字段所占的行，占几行就填几
        params.setHeadRows(1);
        params.setNeedSave(false);
        List<BlackListImportExcel> blackListImportExcelList = ExcelImportUtil.importExcel(file.getInputStream(), BlackListImportExcel.class, params);
        if(CollectionUtils.isEmpty(blackListImportExcelList)){
            return;
        }
        List<BlackListImportExcel> finalList = new ArrayList<>();
        //不同版本的excel有时存在导入的内容中所有字段都为空的情况，此处需要排查
        blackListImportExcelList = blackListImportExcelList.stream().filter(e->!ExcelCheckUtils.isAllFieldNull(e)).collect(Collectors.toList());
        blackListImportExcelList.forEach(e->{
            if(!ExcelCheckUtils.isAllFieldNull(e)){
                finalList.add(e);
            }
        });
        for (BlackListImportExcel importExcel:finalList){
            String idNumber = importExcel.getIdNumber();
            String fileName = importExcel.getAvatar();
            String fullName = importExcel.getFullName();
            String avatar = importExcel.getAvatar();
            File importFile = new File(fileName);
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(importFile);
                MultipartFile multipartFile = new MockMultipartFile(importFile.getName(), importFile.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                try {
                    // TODO: 2022/3/24 上传图片到文件服务器
//                    String avatarUrl = fdfsToolsUtil.uploadFile(multipartFile);
                    //上传完之后删除图片
                    importFile.delete();
                } catch (Exception e) {
                    log.error("上传姓名为"+ fullName +"黑名单图片失败", e);
                }
            } catch (Exception e) {
                log.error("文件中姓名为"+ fullName +"图片转换异常",e);
            }
        }
    }

    /**
     * 导出文件到浏览器
     * @param response
     * @throws Exception
     */
    @GetMapping("/exportExcel1")
    public void exportExcel1(HttpServletResponse response) throws Exception {
        List<BlackListExportExcel> blackListExportExcelList = new ArrayList<>();
        BlackListExportExcel blackListExportExcel = new BlackListExportExcel();
        blackListExportExcel.setFullName("导出测试1");
        blackListExportExcel.setSex(1);
        File file = new File("F:\\a.png");
        //此处也可以读取网络上的资源为字节数组
        byte[] bytes = FileUtils.readFileToByteArray(file);
        //当@Excel注解中imageType=2，则需要导出图片的数据为字节数组
        //当@Excel注解中imageType=1或者不填（默认为1），则是读取本地文件进行导出，个人认为字节数组更常用，无需将文件保存本地后再导出
        blackListExportExcel.setAvatar(bytes);
        blackListExportExcelList.add(blackListExportExcel);
        Workbook workbook = ExcelExportUtil.exportExcel( new ExportParams(),
                BlackListExportExcel.class, blackListExportExcelList);
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("导出测试.xls", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();

        //导出到本地
//        File savefile = new File("F:/excel/");
//        if (!savefile.exists()) {
//            savefile.mkdirs();
//        }
//        FileOutputStream fos = new FileOutputStream("F:/excel/导出测试.xls");
//        workbook.write(fos);
//        fos.close();
    }

    /**
     * 导出文件到本地
     * @param response
     * @throws Exception
     */
    @GetMapping("/exportExcel2")
    public void exportExcel2(HttpServletResponse response) throws Exception {
        List<BlackListImportExcel> blackListImportExcelList = new ArrayList<>();
        BlackListImportExcel blackListImportExcel = new BlackListImportExcel();
        blackListImportExcel.setFullName("导出测试2");
        blackListImportExcel.setSex(1);
        //当@Excel注解中imageType=2，则需要导出图片的数据为字节数组
        //当@Excel注解中imageType=1或者不填（默认为1），则是读取本地文件进行导出，个人认为字节数组更常用，无需将文件保存本地后再导出
        blackListImportExcel.setAvatar("F:\\a.png");
        blackListImportExcelList.add(blackListImportExcel);
        Workbook workbook = ExcelExportUtil.exportExcel( new ExportParams(),
                BlackListImportExcel.class, blackListImportExcelList);
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("导出测试.xls", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

}
